#!/bin/bash

# K8s MCP 工具功能测试脚本

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
BINARY="$PROJECT_ROOT/bin/k8s-mcp-server"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 创建临时管道用于测试
setup_test_env() {
    # 创建临时目录
    TEST_DIR="/tmp/k8s-mcp-test-$$"
    mkdir -p "$TEST_DIR"
    
    # 创建输入和输出管道
    INPUT_PIPE="$TEST_DIR/input"
    OUTPUT_PIPE="$TEST_DIR/output"
    
    mkfifo "$INPUT_PIPE" "$OUTPUT_PIPE"
    
    echo "$TEST_DIR"
}

# 清理测试环境
cleanup_test_env() {
    local test_dir=$1
    if [ -d "$test_dir" ]; then
        rm -rf "$test_dir"
    fi
}

# 发送MCP消息并获取响应
send_mcp_message() {
    local message="$1"
    local timeout_seconds=${2:-5}
    
    log_info "发送MCP消息: $message"
    
    # 启动MCP服务器并发送消息
    (
        cd "$PROJECT_ROOT"
        echo "$message" | "$BINARY" 2>/dev/null
    ) &
    
    local server_pid=$!
    
    # 等待响应
    sleep "$timeout_seconds"
    
    # 停止服务器
    kill "$server_pid" 2>/dev/null || true
    wait "$server_pid" 2>/dev/null || true
}

# 测试工具列表
test_tools_list() {
    echo "=========================================="
    echo "         测试工具列表"
    echo "=========================================="
    
    local message='{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
    
    log_info "请求工具列表..."
    send_mcp_message "$message" 3
    
    echo
}

# 测试集群信息获取
test_cluster_info() {
    echo "=========================================="
    echo "         测试集群信息获取"
    echo "=========================================="
    
    local message='{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "k8s_get_cluster_info", "arguments": {}}}'
    
    log_info "获取集群信息..."
    send_mcp_message "$message" 5
    
    echo
}

# 测试节点信息获取
test_nodes_info() {
    echo "=========================================="
    echo "         测试节点信息获取"
    echo "=========================================="
    
    local message='{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "k8s_get_nodes", "arguments": {"output_format": "wide"}}}'
    
    log_info "获取节点信息..."
    send_mcp_message "$message" 5
    
    echo
}

# 测试命名空间获取
test_namespaces() {
    echo "=========================================="
    echo "         测试命名空间获取"
    echo "=========================================="
    
    local message='{"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "k8s_get_namespaces", "arguments": {}}}'
    
    log_info "获取命名空间列表..."
    send_mcp_message "$message" 5
    
    echo
}

# 测试Pod信息获取
test_pods_info() {
    echo "=========================================="
    echo "         测试Pod信息获取"
    echo "=========================================="
    
    local message='{"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "k8s_get_pods", "arguments": {"namespace": "default", "output_format": "wide"}}}'
    
    log_info "获取Pod信息..."
    send_mcp_message "$message" 5
    
    echo
}

# 直接测试kubectl连接
test_kubectl_direct() {
    echo "=========================================="
    echo "         直接测试kubectl连接"
    echo "=========================================="
    
    log_info "设置KUBECONFIG环境变量..."
    export KUBECONFIG="$PROJECT_ROOT/config/kube-config"
    
    log_info "测试kubectl cluster-info..."
    if kubectl cluster-info 2>/dev/null; then
        log_success "kubectl 连接正常"
    else
        log_error "kubectl 连接失败"
    fi
    
    log_info "测试kubectl get nodes..."
    if kubectl get nodes --no-headers 2>/dev/null; then
        log_success "节点信息获取正常"
    else
        log_error "节点信息获取失败"
    fi
    
    log_info "测试kubectl get namespaces..."
    if kubectl get namespaces --no-headers 2>/dev/null; then
        log_success "命名空间信息获取正常"
    else
        log_error "命名空间信息获取失败"
    fi
    
    echo
}

# 测试MCP服务器基本启动
test_server_startup() {
    echo "=========================================="
    echo "         测试MCP服务器启动"
    echo "=========================================="
    
    log_info "测试服务器基本启动..."
    
    # 启动服务器并立即停止
    (
        cd "$PROJECT_ROOT"
        echo '{"jsonrpc": "2.0", "id": 0, "method": "ping"}' | "$BINARY" 2>/dev/null &
        SERVER_PID=$!
        sleep 2
        kill "$SERVER_PID" 2>/dev/null || true
        wait "$SERVER_PID" 2>/dev/null || true
    )
    
    if [ $? -eq 0 ] || [ $? -eq 143 ]; then  # 143 是SIGTERM的退出码
        log_success "MCP服务器可以正常启动"
    else
        log_error "MCP服务器启动失败"
    fi
    
    echo
}

# 手动交互测试说明
show_manual_test_instructions() {
    echo "=========================================="
    echo "         手动交互测试说明"
    echo "=========================================="
    
    log_info "由于MCP协议的交互性质，建议进行手动测试："
    echo
    echo "1. 启动MCP服务器:"
    echo "   cd $PROJECT_ROOT"
    echo "   ./bin/k8s-mcp-server"
    echo
    echo "2. 在另一个终端发送MCP消息:"
    echo "   # 获取工具列表"
    echo '   echo '\''{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'\'' | nc localhost 8080'
    echo
    echo "   # 获取集群信息"
    echo '   echo '\''{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "k8s_get_cluster_info", "arguments": {}}}'\'' | nc localhost 8080'
    echo
    echo "3. 或使用HTTP模式:"
    echo "   export SERVER_MODE=http"
    echo "   ./bin/k8s-mcp-server"
    echo
    echo "4. 然后使用curl测试:"
    echo '   curl -X POST http://localhost:8080/mcp -H "Content-Type: application/json" -d '\''{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'\'''
    echo
}

# 主测试函数
main() {
    echo "K8s MCP 工具功能测试"
    echo "项目路径: $PROJECT_ROOT"
    echo "二进制文件: $BINARY"
    echo
    
    # 检查二进制文件
    if [ ! -f "$BINARY" ]; then
        log_error "二进制文件不存在: $BINARY"
        log_info "请先编译项目: cd src && go build -o ../bin/k8s-mcp-server ."
        exit 1
    fi
    
    # 检查kubeconfig
    if [ ! -f "$PROJECT_ROOT/config/kube-config" ]; then
        log_error "kubeconfig文件不存在"
        exit 1
    fi
    
    # 运行测试
    test_server_startup
    test_kubectl_direct
    show_manual_test_instructions
    
    echo "=========================================="
    echo "         自动化测试完成"
    echo "=========================================="
    log_info "基础功能测试已完成，建议进行手动交互测试以验证完整功能"
}

# 运行主函数
main "$@" 